<?php
$document_root = $_SERVER['DOCUMENT_ROOT'];
$trailing_char = substr($_SERVER['DOCUMENT_ROOT'], strlen($_SERVER['DOCUMENT_ROOT']) - 1, 1);

if($trailing_char == "/"){
    $document_root = substr($_SERVER['DOCUMENT_ROOT'], 0, strlen($_SERVER['DOCUMENT_ROOT']) - 1);
}

define("SM_CONFIG_FULL_PATH", $document_root . "/sm-transmitter-config.ini"); // sets the path of the config file

require_once("SMTransmitter.class.php");
require_once("Reporter.interface.php");
require_once("CurlReporter.class.php");
require_once("SMMessage.class.php");
require_once("Converter.class.php");

// register error handlers
set_error_handler("SMCustomErrorHandler");
register_shutdown_function("SMShutdown");


function SMCustomErrorHandler($errno, $errstr, $errfile, $errline){
    // get configuration variables
    $vars = parse_ini_file(SM_CONFIG_FULL_PATH);

    // get transmitter url
    $transmitter_base_url = deriveTransmitterBaseUrl();

    // create error package object and contained error object
    $sm_error_package = SMMessagePackage::getInstance($vars['application_key'], $transmitter_base_url);

    // contained error object
    $sm_error_package->addSMMessage(new SMMessage($errno, $errstr, $errfile, $errline));

    return false; // this returns error handling to default handler
}

function SMShutdown(){
    // this function handles fatal errors
    $last_error = error_get_last();
    if($last_error['type'] == E_ERROR || $last_error['type'] == E_USER_ERROR){
        SMCustomErrorHandler($last_error['type'], $last_error['message'], $last_error['file'], $last_error['line']);
    }

    // get configuration variables
    $vars = parse_ini_file(SM_CONFIG_FULL_PATH);

    // get transmitter url
    $transmitter_base_url = deriveTransmitterBaseUrl();

    // create error package object and contained error object
    $sm_error_package = SMMessagePackage::getInstance($vars['application_key'], $transmitter_base_url);

    // create package converter
    $converter = SerializePackageConverter::getInstance();
    
    // get post content
    $content = $converter->convert($sm_error_package);
    
    // create transmitter object
    $transmitter = SMTransmitter::getInstance(SockReporter::getInstance());

    // TODO: first check if script has ended before sending message
    $transmitter->sendMessage($content, $vars['receiver_url']);

}

function deriveTransmitterBaseUrl(){
    $prefix = (isset($_SERVER['HTTPS'])) ? "https://" : "http://";
    return $prefix . $_SERVER['SERVER_NAME'];
}

?>